package org.esk.dablog.gwt.dablog.client;

import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import org.esk.dablog.gwt.dablog.client.model.ClientForumPostEntry;
import org.esk.dablog.gwt.dablog.client.model.ClientForumComment;

import java.util.List;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;

/**
 * This class handles forum's post entry
 * User: esk
 * Date: 06.01.2007
 * Time: 0:34:29
 * $Id:$
 */
public class ForumPostEntryHandler implements TreeItemHandler {
    private EntryGWTServiceAsync entryService;

    public ForumPostEntryHandler(EntryGWTServiceAsync entryService) {
        this.entryService = entryService;
    }


    public void handle(final TreeItem item) {
        ClientForumPostEntry post = (ClientForumPostEntry) item.getUserObject();
        if (item.getState()) {
            entryService.listPostComments(post.getId(), new AsyncCallback() {

                public void onFailure(Throwable caught) {
                }

                public void onSuccess(Object result) {
                    List comments = (List) result;
                    item.removeItems();
                    Map items = new HashMap();
                    for (Iterator r = comments.iterator(); r.hasNext();) {
                        ClientForumComment c = (ClientForumComment) r.next();
                        ForumEntryWidget entry = new ForumEntryWidget(c);
                        TreeItem newItem = item.addItem(entry);
                        newItem.setUserObject(c);
                        items.put(c, newItem);
                    }
                    for (Iterator r = comments.iterator(); r.hasNext();) {
                        ClientForumComment c = (ClientForumComment) r.next();
                        if (c.getParent() != null) {
                            TreeItem item = (TreeItem) items.get(c);
                            item.getParentItem().removeItem(item);
                            TreeItem parent = (TreeItem) items.get(c.getParent());
                            parent.addItem(item);
                            if(!parent.getState()) {
                                parent.setState(true, true);
                            }
                        }
                    }
                    item.addItem("comment on this");
                }
            });
        } else {
            item.removeItems();
            //add empty item to keep node expandable
            item.addItem("");
        }
    }
}